<?php

namespace XWAM\Addon\POrgProduct\Model;

/**
 * 商品类别数据库模型
 *
 * @since 1.0.0 <2015-11-23> SoChishun <14507247@qq.com> Added.
 */
class ProductCategoryModel extends \XWAM\Model\AppbaseModel {

    /**
     * 数据表名称
     * @var string
     */
    protected $tableName = 't_porg_product_category';

    /**
     * 是否批量验证
     * @var boolean
     */
    protected $patchValidate = true;

    function select_tree($select_options = array(), $data_options = array()) {
        $select_options = array_merge(array('field' => 'id, title, pid,sort, status, create_time', 'order' => 'sort, id'), $select_options);
        return $this->base_get_tree_list($select_options, $data_options);
    }

    function select_json_tree($select_options = array(), $data_options = array()) {
        $select_options = array_merge(array('field' => 'id, title as text', 'order' => 'sort, id'), $select_options);
        return $this->base_get_tree_list($select_options,$data_options);
    }

    /**
     * 保存类别
     * @return true|string|array
     * @since 1.0 2015-3-6 by sutroon
     */
    public function save_category() {
        $rules = array(
            array('title', 'require', '类别标题必须填写!'),
            array('status', 'number', '状态有误!'),
        );
        if (!$this->validate($rules)->create()) {
            $this->returnMsg(false, $this->getError());
        }
        if ($this->data['id']) {
            $result = $this->save();
        } else {
            $result = $this->add();
        }
        return $this->returnMsg($result);
    }

    /**
     * 复制类别
     * @return type
     * @since 1.0 <2015-10-28> SoChishun Added.
     */
    function copy_category($id) {
        $table = $this->tableName;
        M()->execute("insert into $table (title,`code`,rules) select concat(title,'_new'),`code`,rules from $table where id=$id");
        return $this->returnMsg(true);
    }

    public function delete_category($id = '') {
        if (!$id) {
            return $this->returnMsg(false, '参数无效');
        }
        // 判断是否有子项目
        $table = $this->tableName;
        $list = M()->query('select a.title from ' . $table . ' a inner join ' . $table . ' b on b.pid=a.id where b.pid in (' . $id . ')');
        $names = false;
        if ($list) {
            foreach ($list as $row) {
                $names.=',' . $row['name'];
            }
        }
        if ($names) {
            return $this->returnMsg(false, '以下项目有子项目,请先转移子项目:' . "\n" . ltrim($names, ','));
        }
        // 判断是否有引用
        $category_ids = M('t_porg_product')->where(array('category_id' => array('in', $id)))->getField('category_id', true);
        if ($category_ids) {
            $names = $this->where(array('id' => array('in', $category_ids)))->getField('title', true);
            return $this->returnMsg(false, '以下项目正在被商品使用,无法删除:' . "\n" . implode(',', $names));
        }
        $result = $this->delete($id);
        return $this->returnMsg($result);
    }

}
